package com.guxingke.typecho4j.widget.provider.content;

import java.util.HashMap;
import java.util.Map;

import com.guxingke.typecho4j.Typecho4jException;
import com.guxingke.typecho4j.jfinal.model.Content;
import com.guxingke.typecho4j.util.ControllerUtil;
import com.guxingke.typecho4j.widget.WidgetProvider;
import com.guxingke.typecho4j.widget.provider.ContentBaseWidget;
import com.jfinal.core.Controller;

/**
 * 独立页内容组件<br>
 * 
 * @author guxingke
 * */
public class PageWidget extends ContentBaseWidget implements WidgetProvider {
	private Map<String, Content> pageCache = new HashMap<String, Content>();

	@Override
	public void excute(Controller controller) throws Typecho4jException {
		String slug = ControllerUtil.getUrlPara(controller);
		Content page = getPage(slug);
		if (page == null) {
			throw new Typecho4jException(404);
		}
		controller.setAttr("page", page);
		controller.setAttr("commentsNum", page.get("commentsNum"));
	}

	private Content getPage(String slug) {
		if (pageCache.containsKey(slug)) {
			return pageCache.get(slug);
		}
		Content result = getPageBySlug(slug);
		if (result != null) {
			pageCache.put(slug, result);
		}
		return result;
	}

	@Override
	public void refresh() {
		// 重置缓存
		this.pageCache.clear();
	}
}
